<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>chat room</title>
<script type='text/javascript' src='dwr/interface/ChatRoom.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<!--<script type='text/javascript' src='dwr/util.js'></script>-->
<link type="text/css" href="css/jquery-ui-1.8.6.custom.css" rel="stylesheet" />	
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.layout.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>
<style>
body {
	font-size: 62.5%;
}

label,input {
	display: block;
}

input.text {
	margin-bottom: 12px;
	width: 95%;
	padding: .4em;
}

fieldset {
	padding: 0;
	border: 0;
	margin-top: 25px;
}

h1 {
	font-size: 1.2em;
	margin: .6em 0;
}

div#users-contain {
	width: 350px;
	margin: 20px 0;
}

div#users-contain table {
	margin: 1em 0;
	border-collapse: collapse;
	width: 100%;
}

div#users-contain table td,div#users-contain table th {
	border: 1px solid #eee;
	padding: .6em 10px;
	text-align: left;
}

.ui-dialog .ui-state-error {
	padding: .3em;
}

.validateTips {
	border: 1px solid transparent;
	padding: 0.3em;
}
.messageDaligDiv{
overflow-y: auto; height: 250px; width: 450px;
}
</style>
<script>
    //当前用户用户名
    var username='';
    //是否点击了注销按钮
    var logoutbutton=false;
    //聊天框信息编辑器toolbar
	var config = {toolbar: [
	                    	['Cut','Copy','Paste','PasteText','PasteFromWord'],
	            		    ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	            		    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
	            		    '/',
	            		    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
	            		    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
	            		    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
	            		    ['Link','Unlink'],
	            		    ['Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
	            		    '/',
	            		    ['Styles','Format','Font','FontSize'],
	            		    ['TextColor','BGColor'],
	            		    ['Maximize', 'ShowBlocks']
	            		]};
	/**init start*/
	$(function() {
	    //exception
	    function errh(msg, exc) {
		    alert("Error message is: " + msg + " - Error Details: ");
				//+ dwr.util.toDescriptiveString(exc, 2));
	    }
	    //初始化好异常信息
	    dwr.engine.setErrorHandler(errh);
		//初始化用户名
		username='';
		//初始化注销信息
		logoutbutton=false;
		
		//开始获取信息		
		ChatRoom.getUserInfo(function(usernameinfo){
			//没有登陆
			if(usernameinfo=='nouser'||usernameinfo==''){
				//存在错误，需要初始化登陆dialog
				alert('登录发生了错误！');
				window.location.replace('login.html');
			}else{
				//用户已经登陆完毕
				//获得用户名称
				username=usernameinfo;
				$('#welcome').html("<h1>welecome&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+usernameinfo+"^-^</h1>");
				//关闭浏览器时提示					
				window.onbeforeunload = function() {
					//如果点击了注销按钮，什么也不做
					if(logoutbutton){
					}else{
					   return "离开或刷新当前页面将导致注销操作，确定继续？";
					}
				};
				window.onunload = function() {
					//如果点击了注销按钮，什么也不做
					if(logoutbutton){
					}else{
						onunloadlogout();
						alert('欢迎您的使用');
					}
				};
				//添加注销button
				$("#logoutbuttons").append("<button id='logout'>注销</button>");					
				//注销button
				$("#logout").button().click(function() {
					logout();
				});
				//添加布局
				$('body').layout({
					applyDefaultStyles : true
				});
				//获得所有登陆的用户的信息
				//用户刚刚登录时，获得所有用户信息
				ChatRoom.getAllUsers(function(users){
				   $.each(users,function(i,user){
						//如果不是当前用户
						if(user!=username){
							//添加到用户列表
							addButton(user);
						}
				   });	
				});
				//设置dwr
				//初始化dwr反转控制
				dwr.engine.setActiveReverseAjax(true);
		  }
		});		
	});
	/**init end*/
	
	/**** 布局区  start*/
	//添加按钮
	function addButton(id){
		$('#buttons').append("<button id='create-user"+id+"'>Create new user"+id+"</button>");
		$("#create-user"+id).button()
	    .click(function() {
	    	addForm(id);
			  //展示的form数量加1
	    	formShowCount=formShowCount+1;
			$("#dialog-form"+id).dialog("open");
			//如果显示的form数量等于1，需要记录其位置
			if(formShowCount==1){
			   positions=$("#dialog-form"+id).offset();			   
			}
			//如果显示的form数量大于1，dialog数量需要偏移
			if(formShowCount>1){
				$("#dialog-form"+id).dialog("option","position",[positions.left+(25*(formShowCount-1)),positions.top+(25*(formShowCount-1))]);
			}
			$(this).button({ disabled: true });
		});
	}
	//设置弹出框的显示位置
	var positions='center';
	//显示的form的个数
	var formShowCount=0;
	//添加form dialog弹出框表单
	function addForm(id){	
		//如果还未创建这个div进行创建，并且初始化dialog
		if($('#dialog-form'+id).length<1){	
		   var formdiv="<div id='dialog-form"+id+"' title='与--"+id+"--的对话'><div id='show"+id+"' class='messageDaligDiv'></div><form id='form"+id+"' name=''form"+id+"' method='post'> <input type='hidden' name='toUserName' readonly='readonly' id='toUserName"+id+"' value='"+id+"'/><br /> 聊天内容：<textarea class='editorer' rows='4' cols='70' name='message' id='message"+id+"'></textarea><br /> <label id='formLabel"+id+"'></label> <button type='button' id='submitButton"+id+"' name='messageSubmit' onclick=\"sendMessage('"+id+"');\">提交</button><script type='text/javascript'>$('#message"+id+"').ckeditor(config);</scri"+"pt></form></div>";
	       $('#forms').append(formdiv);
	       //初始化dialog
	    	$('#dialog-form'+id).dialog({
				autoOpen: false,
				position:'center',
				height: 500,
				width: 500,
				modal: false,
				close: function() {
					  //展示的form数量减去1
		    		  formShowCount=formShowCount-1;
					$("#create-user"+id).button({ disabled: false });
				}
			});
	    }
	}
	/**** 布局区 end*/


	/*******AJAX 与后台交互   start   */
	//关闭或者刷新页面时的注销操作
	function onunloadlogout() {
		//执行注销操作//需要同步请求
		ChatRoom.logout({callback:function(data){},async:true});
	}
	//注销操作
	function logout() {
		//执行注销操作//需要同步请求
		ChatRoom.logout({callback:function(data){
			if (data == 'success') {
				//注销成功，设置点击了注销按钮，然后跳转到登录页面
			    logoutbutton=true;
				window.location.replace('login.html');
			}else{
				alert('注销失败，请重试');
			}
		},async:true});
	}
	//当前发送消息
	function sendMessage(id) {
		var toUserName=$('#toUserName'+id).val();
		var message=$('#message'+id).val();
		ChatRoom.sendMessage(toUserName,message,function(data){
			if (data=='success') {
			   //发送消息成功了,清空消息框
			   $('#message'+id).val('');
			   $('#message'+id).focus();
				
			} else {
				if (data == 'nouser') {
					alert('这个用户还未登录');
				}else{
					alert('消息发送失败，请重新发送！');
					//alert(data);
				}
			}
		});
	}

	
	//接收登陆的用户
	function loginUsers(user) {
		//如果不是当前用户
		if(user!=username){
			//添加到用户列表
			addButton(user);
		}
	}
	//接收下线的用户
	function logoutUsers(user) {
		//删除按钮
		$("#create-user" + user).remove();
		//删除dialog
		if ($('#dialog-form' + user).length >= 1) {
			$('#dialog-form' + user).dialog("destroy");
			$('#dialog-form' + user).remove();
		}		
	}
	
	////接受消息   添加消息到div
	function appendMessage(toUserName, authorName,time,message) {
		//当前登陆者是接受消息者	  则显示消息在作者对话框上
		var id=authorName;
		//如果是当前登陆者发送的消息，则显示消息在接受者对话框上
		  if(authorName==username){
			  id=toUserName;
		  }
	      //如果还未开始进行通话，先创建对话form，然后打开，输入内容
	      if ($("#show" + id).length < 1) {
		     addForm(id);
		  	 //展示的form数量加1
	  	     formShowCount = formShowCount + 1;
		  	 // $("#dialog-form"+id).dialog("open");
		  }
	      $("#show" + id).append('' + authorName + '&nbsp;&nbsp;&nbsp;[' + time + ']:'+ message + '<br/>');
	       //设置滚动条到消息查看div底部
	      $("#show" + id).scrollTop(100000);
	}
	/*******AJAX 与后台交互   end   */

</script>
</head>
<body>
<DIV class="ui-layout-center">
<div id='forms'></div>
</DIV>
<DIV class="ui-layout-north">
<center><div id='welcome'></div></center>
<div id='logoutbuttons'></div>
</DIV>
<DIV class="ui-layout-south">
</DIV>
<DIV class="ui-layout-east">
<div id='buttons'></div>
</DIV>
</body>
</html>